package com.hunttown.mes.manage.controller._iot;

import com.hunttown.mes.common.utils.IpUtils;
import com.hunttown.mes.common.utils.SystemUtils;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.manage.service.IotAlarmTriggerConditionManageService;
import com.hunttown.mes.manage.service.IotAlarmTriggerManageService;
import com.hunttown.mes.manage.service.TransportOperateLogManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.IotAlarmTriggerConditionDTO;
import com.hunttown.mes.rpc.domain.IotAlarmTriggerDTO;
import com.hunttown.mes.rpc.domain.enums.iot.alarm.AlarmMethodEnum;
import com.hunttown.mes.rpc.domain.enums.iot.alarm.TriggerLevelEnum;
import com.hunttown.mes.rpc.domain.enums.iot.alarm.TriggerTypeEnum;
import com.hunttown.mes.rpc.domain.query.IotAlarmTriggerDTOQuery;
import com.hunttown.common.domain.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * created by wangjunfu on 2021-03-04 19:17:08
 */
@Controller
@RequestMapping(value = "/iot/alarm")
public class AlarmTriggerController {

    private final static Logger logger = LoggerFactory.getLogger(AlarmTriggerController.class);

    private final IotAlarmTriggerManageService iotAlarmTriggerService;
    private final IotAlarmTriggerConditionManageService conditionManageService;
    private final ModelService modelService;
    private final AnalysisManageManageService manageService;
    private final TransportOperateLogManageService logService;

    @Autowired
    public AlarmTriggerController(IotAlarmTriggerManageService iotAlarmTriggerService, IotAlarmTriggerConditionManageService conditionManageService, ModelService modelService, AnalysisManageManageService manageService, TransportOperateLogManageService logService) {
        this.iotAlarmTriggerService = iotAlarmTriggerService;
        this.conditionManageService = conditionManageService;
        this.modelService = modelService;
        this.manageService = manageService;
        this.logService = logService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return model
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model, IotAlarmTriggerDTOQuery dtoQuery) {

        dtoQuery.setOrderBy("order by id desc");
        Page<IotAlarmTriggerDTO> dataPage = iotAlarmTriggerService.getForPage(dtoQuery);

        IotAlarmTriggerConditionDTO conditionDTO;
        for (IotAlarmTriggerDTO item : dataPage.getItems()) {
            item.setSolveName(modelService.getManageName(item.getSolveId()));

            conditionDTO = conditionManageService.getFromCacheId(item.getTriggerId());
            if (conditionDTO == null) {
                continue;
            }
            item.setTriggerTypeName(TriggerTypeEnum.getEnumByKey(conditionDTO.getTriggerType()));
            item.setTriggerLevelName(TriggerLevelEnum.getEnumByKey(conditionDTO.getTriggerLevel()));
            item.setAlarmMethodName(AlarmMethodEnum.getEnumByKey(conditionDTO.getAlarmMethod()));
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        return "iot/alarm/index";
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return model
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        IotAlarmTriggerDTO obj = new IotAlarmTriggerDTO();
        obj.setId(id);

        if (id > 0) {
            obj = iotAlarmTriggerService.getById(id);
        }
        iotAlarmTriggerService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //endregion

    //region 解决报警

    /**
     * 解决报警
     *
     * @param model model
     * @param id    ID
     * @return model
     */
    @RequestMapping(value = "/solveAlarm", method = RequestMethod.POST)
    public String solveAlarm(HttpServletRequest request, Model model, Integer id) {
        id = (id == null ? 0 : id);

        if (id > 0) {
            IotAlarmTriggerDTO obj = iotAlarmTriggerService.getById(id);

            if (obj != null && (obj.getSolveId() == null || obj.getSolveId() <= 0)) {
                String pin = AdminBaseClass.getPin(request);
                AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
                obj.setSolveId(curr_obj.getId());
            }

            model.addAttribute("AlarmObj", obj);
            modelService.getManagerPage(model);
        }

        return "iot/alarm/solve-alarm-modal";
    }

    /**
     * 保存解决报警
     *
     * @param request      request
     * @param alarmId      报警ID
     * @param solveId      解决人ID
     * @param solveProcess 解决经过
     * @return json
     */
    @RequestMapping(value = "/saveSolveAlarm", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveSolveAlarm(HttpServletRequest request, Integer alarmId, Integer solveId, String solveProcess) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        if (alarmId == null || alarmId <= 0) {
            map.put("returnMessage", "报警信息保存异常！");
            return map;
        }

        IotAlarmTriggerDTO obj = iotAlarmTriggerService.getById(alarmId);

        IotAlarmTriggerDTO update = new IotAlarmTriggerDTO();
        update.setId(alarmId);
        update.setSolveId(solveId);
        update.setSolveTime(new Date());
        if (obj.getCloseTimeSr().equals("1990-01-01 00:00:00")) {
            update.setCloseTime(new Date());
        }
        update.setSolveProcess(solveProcess);
        boolean isNext = iotAlarmTriggerService.updateInfoById(update);

        //region *** 更新信息完毕记录操作日志 ***
        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
        logService.insertSimple(1, 146, alarmId, 2,
                "保存报警解决信息",
                (isNext ? "成功" : "失败") + "：" + solveProcess,
                curr_obj.getId(),
                IpUtils.getClientIp(request),
                SystemUtils.getBrowserInfo(request));
        //endregion

        map.put("returnCode", 1);
        map.put("returnMessage", "报警解决成功！");

        return map;
    }

    //endregion

}